﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataContexts;

public partial class Admin_User_AddEdit : System.Web.UI.Page
{
    private UserDataContext userCntx = new UserDataContext();


    public int UserId
    {
        get
        {
            return Helper.QSIntValue("id");
        }
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        ((BaseMasterPage)this.Master).CurrentPage = PageConfig.Pages.AdminUserAddEdit;
        if (!((BaseMasterPage)this.Master).AuthorizeCurrentUser())
            return;

        if (!IsPostBack)
        {
            LoadUserTypes();
            trConfirmPassword.Visible = (UserId == 0);
            trPassword.Visible = (UserId == 0);

            if (UserId > 0)
            {
                User user = userCntx.Users.SingleOrDefault(obj => obj.UserId == UserId);
                //CONTROL ASSIGNMENT
                txtUsername.Text = user.Username;
                txtPassword.Text = user.Password;
                txtEmailAddress.Text = user.EmailAddress;
                ddlUserType.SelectedValue = user.UserType.Value.ToString();
                chkActive.Checked = user.Active.Value;
            }
        }
    }

    private void LoadUserTypes()
    {
        ddlUserType.DataSource = userCntx.UserTypes;
        ddlUserType.DataTextField = "UserTypeName";
        ddlUserType.DataValueField = "UserTypeId";
        ddlUserType.DataBind();
        ddlUserType.Items.Insert(0, new ListItem("Select User Type", "0"));
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        User user = new User();
        if (UserId > 0)
            user = userCntx.Users.SingleOrDefault(obj => obj.UserId == UserId);

        //PROPERTY ASSIGNMENT
        user.Username = txtUsername.Text;
        if (UserId == 0)
            user.Password = txtPassword.Text;
        user.EmailAddress = txtEmailAddress.Text;
        user.UserType = Convert.ToInt32(ddlUserType.SelectedValue);
        user.Active = chkActive.Checked;

        if (UserId == 0)
            userCntx.Users.InsertOnSubmit(user);

        userCntx.SubmitChanges();

        Response.Redirect("default.aspx");
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("default.aspx");
    }
}
